import axios from 'axios'

const userHttp = axios.create({
    baseURL: process.env.VUE_APP_API_BASE_URL || 'http://localhost:8300', // 后端地址
    timeout: 10000,
    withCredentials: true,  // 必须开启，与后端 AllowCredentials 匹配
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
userHttp.interceptors.request.use(
    (config) => {
        console.log('请求:', config.url, config.method, config.data)

        // 特殊处理登录请求 - 转换为URL编码格式（Spring Security表单登录要求）
        if (config.url === '/auth/login') {
            if (config.data instanceof URLSearchParams) {
                config.data = config.data.toString();
                config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
            }
        }

        // 添加请求元数据
        config.metadata = {
            startTime: new Date(),
            requestId: Math.random().toString(36).substr(2, 9)
        };

        console.log(`🚀 请求 #${config.metadata.requestId}: ${config.method?.toUpperCase()} ${config.url}`);

        return config
    },
    (error) => Promise.reject(error)
)

// 响应拦截器：处理登录失败响应（状态码200但message为登录失败）
userHttp.interceptors.response.use(
    (response) => {
        const endTime = new Date();
        const duration = endTime - response.config.metadata.startTime;
        console.log(`✅ 响应 #${response.config.metadata.requestId}: ${response.status} (${duration}ms)`, response.data);

        // 登录接口特殊处理：后端返回"登录失败"时抛异常，让前端catch处理
        if (response.config?.url === '/auth/login' && response.data?.message?.includes('登录失败')) {
            const loginError = new Error(response.data.message);
            loginError.response = { status: response.status, data: response.data };
            throw loginError;
        }

        return response.data;
    },
    (error) => {
        // 确保有config对象再访问metadata
        if (error.config && error.config.metadata) {
            const endTime = new Date();
            const duration = endTime - error.config.metadata.startTime;
            console.log(`❌ 响应 #${error.config.metadata.requestId}: ${error.response?.status || 'NETWORK_ERROR'} (${duration}ms)`);
        } else {
            console.log(`❌ 响应错误:`, error.message);
        }

        console.error('响应错误详情:', {
            url: error.config?.url,
            method: error.config?.method,
            status: error.response?.status,
            statusText: error.response?.statusText,
            data: error.response?.data,
            message: error.message
        })

        // 登录错误特殊处理
        if (error.config?.url === '/auth/login') {
            if (error.response && error.response.status === 401) {
                const authError = new Error('登录失败：账号或密码错误');
                authError.response = error.response;
                return Promise.reject(authError);
            }
        }

        return Promise.reject(error)
    }
)

export default userHttp